using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SQLite;
using System.IO;

namespace deckAnalyser.Support
{
  public class DBWrapper
  {
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(DBWrapper));

    private static Dictionary<String, String> attachedDBs = new Dictionary<String, String>();
    private static SQLiteConnection connection = null;

    private static bool isOpen = false;
    public static bool IsOpen { get { return isOpen; } }

    public static void Open(String path, String name)
    {
      if (isOpen) return; 

      connection = new SQLiteConnection("Data Source=" + Path.Combine(path, name)); ;
      connection.Open();
      isOpen = true;
    }

    public static void Close()
    {
      if (!isOpen) return;

      connection.Close();
      isOpen = false;
    }

    public static void Attach(String path, String name, String alias)
    {
      if (!isOpen) Open(path, name);

      DBWrapper.ExecuteNonQuery("attach database '" + Path.Combine(path, name) + "' as " + alias + ";");
    }

    public static int ExecuteNonQuery(string sql)
    {
      int rowsUpdated = 0;
      SQLiteCommand command = new SQLiteCommand(connection);
      command.CommandText = sql;
      rowsUpdated = command.ExecuteNonQuery();
      return rowsUpdated;
    }

    public static DataTable GetDataTable(string sql)
    {
      DataTable retVal = new DataTable();

      SQLiteCommand command = new SQLiteCommand(connection);
      command.CommandText = sql;
      SQLiteDataReader reader = command.ExecuteReader();
      retVal.Load(reader);
      reader.Close();

      return retVal;
    }

    public static string ExecuteScalar(string sql)
    {
      SQLiteCommand command = new SQLiteCommand(connection);
      command.CommandText = sql;
      object value = command.ExecuteScalar();
      if (value != null)
      {
        return value.ToString();
      }
      return "";
    }
  }
}
